package controllers;

import helpers.CookieHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.AutoSiteModel;
import entities.AutoSite;

@SuppressWarnings("serial")
public class AutoSiteProcessServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String strIds = (String) request.getParameter("ids");
	    String action = (String) request.getParameter("action");
	    int status = 0;
	    String[] ids = strIds.split(",");
	    AutoSiteModel autoSiteModel = AutoSiteModel.getInstance();
	    
	    ArrayList<String> statusAction = new ArrayList<String>(Arrays.asList("status_active", "status_inactive"));
	    
	    for (int i = 0; i < ids.length; i++) {
	        if (!ids[i].isEmpty()) {
	        	if(statusAction.contains(action.toLowerCase())) {
	                if (action.equalsIgnoreCase("status_active")) {
	                	status = 1;
					} else if (action.equalsIgnoreCase("status_inactive")) {
						status = 0;
					}

	                AutoSite site = autoSiteModel.get(URLDecoder.decode(ids[i]));
	                if (site != null) {
	                	site.setStatus(status);
	                	autoSiteModel.insert(site);
	        		}
	        	} else if (action.equalsIgnoreCase("delete")) {
	        		AutoSite site = autoSiteModel.get(URLDecoder.decode(ids[i]));
	        		autoSiteModel.delete(site);
				}
	        }
	    }
	    
	    if (action.equalsIgnoreCase("delete")) {
	    	CookieHelper.setCookie(response, "success", "Delete success ids " + strIds);
	    } else if (action.equalsIgnoreCase("status_active")) {
	    	CookieHelper.setCookie(response, "success", "Active success ids " + strIds);
		} else {
			CookieHelper.setCookie(response, "success", "Deactive success ids " + strIds);
		}
	}
}
